import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import type { ActionReducerMapBuilder, AsyncThunk, PayloadAction, Slice } from '@reduxjs/toolkit'
import { getWhiteDevice, GetWhiteDeviceParams } from './whiteDeviceAPI'

interface InitialState {
  params: GetWhiteDeviceParams,
  table: {
    status: 'init' | 'loading' | 'success' | 'error',
    data?:Res
  },
  modal: {
    open: boolean
  }
}

const initialState:InitialState = {
  params: {
    app_params: 'zxcvbn1',
  },
  table: {
    status: 'init'
  },
  modal: {
    open: false
  }
}

type Res = {
  data: string[]
}
export const getWhiteDeviceAsync:AsyncThunk<Res, GetWhiteDeviceParams, {}> = createAsyncThunk<Res, GetWhiteDeviceParams, {}>('whiteDevice/getWhiteDeviceAsync', async params => {
 const res:Res = await getWhiteDevice(params)
 return res
})
const tableStatus = (builder: ActionReducerMapBuilder<InitialState>) => {
  builder.addCase(getWhiteDeviceAsync.pending, state => {
    state.table.status = 'loading'
  }).addCase(getWhiteDeviceAsync.fulfilled, (state, action) => {
    state.table.status = 'success'
    state.table.data = action.payload
  }).addCase(getWhiteDeviceAsync.rejected, state => {
    state.table.status = 'error'
  })
}

type Reducers = {
  changeModal: (state:InitialState, action:PayloadAction<Partial<InitialState['modal']>>) => void
}
type Selectors = {}
const whiteDeviceSlice:Slice<InitialState, Reducers, 'whiteDevice', 'whiteDevice', Selectors> = createSlice<InitialState, Reducers, 'whiteDevice', Selectors, 'whiteDevice'>({
  name: 'whiteDevice',
  initialState,
  reducers:{
    changeModal(state, action){
      state.modal = {
        ...state.modal,
        ...action.payload
      }
    }
  },
  extraReducers(builder){
    tableStatus(builder)
  }
})

export const { changeModal } = whiteDeviceSlice.actions

export default whiteDeviceSlice.reducer